package kg.aibek.projecteuler.p10;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;

import kg.aibek.preuler1.Util;

public class Problem49 {
	public void solve() {
		Set<Integer> set = new TreeSet<Integer>();
		for (int i = 1000; i < 10000; i++) {
			if (Util.isPrime(i)) {
				set.add(i);
			}
		}

		for (Integer i : set) {
			Set<Integer> pSet = permutation(i);
			Set<Integer> nSet = new TreeSet<Integer>();

			for (Integer ii : pSet) {
				if (set.contains(ii)) {
					nSet.add(ii);
				}
			}

			if (nSet.size() >= 3) {
				int nn[] = new int[nSet.size()];
				int ind = 0;
				for (int ii : nSet) {
					nn[ind++] = ii;
				}
				for (int a = 0; a < nSet.size(); a++) {
					for (int b = a + 1; b < nSet.size(); b++) {
						for (int c = b + 1; c < nSet.size(); c++) {
							if (nn[b] - nn[a] == nn[c] - nn[b]) {
								System.out.println(nn[a] + "" + nn[b] + ""
										+ nn[c]);
							}
						}
					}
				}
			}
		}
	}

	private Set<Integer> permutation(int number) {
		List<Integer> list = new ArrayList<Integer>();
		while (number > 0) {
			list.add(number % 10);
			number = number / 10;
		}
		List<String> sList = Util.getPermutation(list);

		Set<Integer> set = new TreeSet<Integer>();
		for (String str : sList) {
			set.add(Integer.parseInt(str));
		}
		return set;
	}

	public static void main(String[] args) {
		Problem49 p = new Problem49();
		p.solve();
	}
}
